import { defineStore } from 'pinia'

export const useTodoStore = defineStore('todo', {
  // 初始化数据 相当于vue的data
  state() {
    return {
      todoList: [],
      filterType: '0'
    }
  },
  // 用于数据推导
  getters: {
    filteredTodoList(state) {
      if (state.filterType === '1') {
        return state.todoList.filter((item) => item.isFinished === false)
      } else if (state.filterType === '2') {
        return state.todoList.filter((item) => item.isFinished === true)
      } else {
        return state.todoList
      }
    }
  },
  // 针对state的数据做 增删改查
  actions: {
    addTodo(text) {
      this.todoList.push({
        id: Date.now(),
        text,
        isFinished: false
      })
    },
    finishTodo(id) {
      // find 查找数组中符合条件的元素 返回该元素
      this.todoList.find((item) => item.id === id).isFinished = true
    },
    removeTodo(id) {
      // 找到id对应的下标 (findIndex 查找数组中符合条件的元素 返回该元素的下标)
      const index = this.todoList.findIndex((item) => item.id === id)
      this.todoList.splice(index, 1)
    },
    setFilterType(type) {
      this.filterType = type
    }
  }
})
